# vim:ts=4:sw=4:noet:
""" Connections to devices """

import socket
import serial
import time

class RemoteConnection:
	def __init__(self):
		self.timeout = 0.5

	def setTimeout(self, to):
		self.timeout = to

class RemoteTcpConnection(RemoteConnection):
	def __init__(self, host="localhost", port=4321, connect=True):
		RemoteConnection.__init__(self)
		self.host = host
		self.port = port
		self.sock = None
		if connect:
			self.connect()

	def connect(self):
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		try:
			self.sock.connect((self.host, self.port))
			self.sock.settimeout(1)
			return True
		except:
			self.sock = None
			return False

	def __del__(self):
		if self.sock:
			self.sock.close()

	def send(self, msg):
		if not self.sock:
			if not self.connect():
				return []
		self.sock.send(msg)

	def recv(self):
		if not self.sock:
			if not self.connect():
				return []
		return self.sock.recv(512)

	def close(self):
		self.sock.close()
		self.sock = None

	def __repr__(self):
		return "<conn tcp %s:%d>" % (self.host, self.port)

class RemoteSerialConnection(RemoteConnection):
	def __init__(self, port="/dev/tty.KeySerial1", baud=115200, connect=True):
		RemoteConnection.__init__(self)
		self.port = port
		self.baud = baud
		if connect:
			self.connect()

	def connect(self):
		self.ser = serial.Serial(self.port, self.baud)
		self.ser.flushInput()
		self.ser.flushOutput()

	def send(self, msg):
		if self.timeout>0.5:
			self.ser.write(msg)
			#for m in msg:
			#	self.ser.write(m)
			#	time.sleep(0.000001)
		else:
			self.ser.write(msg)

	def recv(self):
		timeout =  time.time()+self.timeout
		while not self.ser.inWaiting():
			if (time.time()>timeout):
				return []
		l = ord(self.ser.read(1))
		data = self.ser.read(l-1)
		return chr(l)+data

	def close(self):
		self.ser.close()

	def __repr__(self):
		return "<conn ser %s>" % (self.port)
